package com.tbsoft.ehr.util;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.tbsoft.ehr.model.Agency;
import com.tbsoft.ehr.model.Department;
import com.tbsoft.ehr.model.ServiceCustomer;
import com.tbsoft.ehr.service.agency.AgencyService;
import com.tbsoft.ehr.service.department.DepartmentService;
import com.tbsoft.ehr.service.pubField.PubFieldService;
import com.tbsoft.ehr.service.serviceCustomer.ServiceCustomerService;

public class InitListener implements ServletContextListener {

	private ServletContext context;

	@Override
	public void contextDestroyed(ServletContextEvent event) {
		System.out.println("context init end....");
		context = event.getServletContext();
		context.removeAttribute("AGENCY_LIST");
		context.removeAttribute("DEPT_LIST");
		context.removeAttribute("SC_LIST");
		context.removeAttribute("PUBFIELD_MAP");
		context.removeAttribute("PUBFIELDTYPE_MAP");
	}

	@Override
	public void contextInitialized(ServletContextEvent event) {
		System.out.println("context init start....");
		context = event.getServletContext();
		ApplicationContext springContext = WebApplicationContextUtils
				.getRequiredWebApplicationContext(context);

		ServiceCustomerService scService = (ServiceCustomerService) springContext
				.getBean("serviceCustomerService");
		AgencyService agencyService = (AgencyService) springContext
				.getBean("agencyService");
		DepartmentService deptService = (DepartmentService) springContext
				.getBean("departmentService");
		PubFieldService pubFieldService = (PubFieldService) springContext
				.getBean("pubFieldService");

		List<ServiceCustomer> scLst = scService.getServiceCustomers();
		Collections.sort(scLst);
		List<Agency> agencyLst = agencyService.getAllAgency();
		List<Department> deptLst = deptService.getAllDepts();
		//获取公共字段类型及其名称的key-value对
		Map<String,String> fieldTypeMap = pubFieldService.getPubFieldTypeMap();		
		Map<String, Map> pubFieldTypeMap = pubFieldService.getPubFieldMap();
		
		context.setAttribute("AGENCY_LIST", agencyLst);
		context.setAttribute("DEPT_LIST", deptLst);
		context.setAttribute("SC_LIST", scLst);
		context.setAttribute("PUBFIELD_MAP", pubFieldTypeMap);
		context.setAttribute("PUBFIELDTYPE_MAP", fieldTypeMap);
	}

}
